package com.flqy.baselibrary.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ImageUtils {

    public static Bitmap cropImage(Bitmap source, int x, int y, int width, int height) {
        if (source == null) return null;
        width = Math.min(width, source.getWidth());
        height = Math.min(height, source.getHeight());
        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Rect src = new Rect(x, y, width, height);
        Rect dest = new Rect(0, 0, width, height);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        canvas.drawBitmap(source, src, dest, paint);
        return result;
    }

    public static Bitmap takeViewShot(View view) {
        // View是你需要截图的View
        view.setDrawingCacheEnabled(true);view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();// 获取View长和高
        int width = view.getWidth();
        int height = view.getHeight();Bitmap b = Bitmap.createBitmap(b1, 0, 0, width, height);
        view.destroyDrawingCache();
        return b;
    }

    /**屏幕截图保存*/
    public static void saveScreenShot(Context  context,Bitmap bitmap)  {
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        OutputStream outStream = null;
        String filename;//声明文件名
        //以保存时间为文件名
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss");
        filename =  sdf.format(date);
        File file = new File(extStorageDirectory, filename+".JPEG");//创建文件，第一个参数为路径，第二个参数为文件名
        try {
            outStream = new FileOutputStream(file);//创建输入流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.close();


 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
 Uri uri = Uri.fromFile(file);intent.setData(uri);
 context.sendBroadcast(intent);

 //这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！*/
            Toast.makeText(context,"saved",
                    Toast.LENGTH_SHORT).show();
        } catch(Exception e) {
            Toast.makeText(context, "exception:" + e,
                    Toast.LENGTH_SHORT).show();

        }
    }

}
